<template>
    <el-dialog v-model="props.visible" width="80%" class="rich-chat-dialog" @close="onClose">
        <McLayout class="container">
            <McHeader :title="'AIFlow'" :logoImg="'https://matechat.gitcode.com/logo.svg'">
                <template #operationArea>
                    <div class="operations">
                        <i class="icon-helping"></i>
                    </div>
                </template>
            </McHeader>
            <McLayoutContent v-if="startPage"
                style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px">
                <McIntroduction :logoImg="'https://matechat.gitcode.com/logo2x.svg'" :title="'AIFlow'"
                    :subTitle="'Hi，欢迎使用 AIFlow'" :description="description"></McIntroduction>
                <McPrompt :list="introPrompt.list" :direction="introPrompt.direction" class="intro-prompt"
                    @itemClick="onSubmit($event.label)"></McPrompt>
            </McLayoutContent>
            <McLayoutContent class="content-container" v-else>
                <template v-for="(msg, idx) in messages" :key="idx">
                    <McBubble v-if="msg.from === 'user'" :content="msg.content" :align="'right'"
                        :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg' }">
                    </McBubble>
                    <McBubble v-else :loading="msg.loading ?? false" :avatarConfig="msg.avatarConfig"
                        :variant="'bordered'">
                        <template #default>
                            <div class="think-toggle-btn" @click="toggleThink(idx)">
                                <i class="icon-point"></i>
                                <span>{{ thinkBtnText }}</span>
                                <i :class="btnIcon"></i>
                            </div>
                            <McMarkdownCard :enableThink="true" :content="msg.content" :theme="theme"
                                :mdPlugins="mdPlugins"></McMarkdownCard>
                        </template>
                    </McBubble>
                </template>
            </McLayoutContent>
            <div class="shortcut">
                <div style="flex: 1;">
                    <McPrompt v-if="!startPage" :list="simplePrompt" :direction="'horizontal'" style="flex: 1"
                        @itemClick="onSubmit($event.label)"></McPrompt>
                </div>
                <el-tooltip content="新建会话" placement="top" effect="light">
                    <div class="botton" @click="newConversation">
                        <el-icon :size="20">
                            <AddThree theme="outline" size="24" fill="#333" />
                        </el-icon>
                    </div>
                </el-tooltip>
            </div>
            <McLayoutSender>
                <McInput :value="inputValue" :loading="isLoading" :maxLength="2000" showCount
                    @change="(e) => (inputValue = e)" @submit="onSubmit" />
            </McLayoutSender>
        </McLayout>
    </el-dialog>
</template>

<script setup lang="ts" name="RichChatDialog">
import { type PropType, ref, nextTick, onMounted } from 'vue';
import { AddThree } from '@icon-park/vue-next';
import { ElMessage } from 'element-plus';
import type { FlowAPI } from '@/types/types';
import { parseSSE } from './api/flow-api';
import 'vue-devui/button/style.css';
import { full as emoji } from 'markdown-it-emoji'

const props = defineProps({
    id: {
        type: Number,
        required: true,
    },
    api: {
        type: Object as PropType<FlowAPI>,
        required: true
    },
    visible: {
        type: Boolean,
        default: false,
    },
    onClose: {
        type: Function as () => void,
        required: true,
    }
});

const mdPlugins = ref([{
    plugin: emoji
}])

const thinkBtnText = ref('');
const btnIcon = ref('icon-chevron-up-2');
const isLoading = ref(false);
const theme = ref('light');

const toggleThink = (idx) => {
    if (isLoading.value) {
        return;
    }
    const targetNode = document.querySelectorAll('.mc-bubble-content-container')[idx];
    if (targetNode) {
        const thinkBlock = targetNode.querySelector('.mc-think-block');
        if (thinkBlock && thinkBlock instanceof HTMLElement) { // 类型判断
            const currentDisplay = getComputedStyle(thinkBlock).display;
            thinkBlock.style.display = currentDisplay === 'none' ? 'block' : 'none';
            btnIcon.value = currentDisplay === 'none' ? 'icon-chevron-up-2' : 'icon-chevron-down-2';
        }
    }
}

const description = [
    'MateChat 可以辅助研发人员编码、查询知识和相关作业信息、编写文档等。',
    '作为AI模型，MateChat 提供的答案可能不总是确定或准确的，但您的反馈可以帮助 MateChat 做的更好。',
];
const introPrompt = {
    direction: 'horizontal',
    list: [
        // {
        //     value: 'quickSort',
        //     label: '帮我写一个快速排序',
        //     iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
        //     desc: '使用 js 实现一个快速排序',
        // },
        // {
        //     value: 'helpMd',
        //     label: '你可以帮我做些什么？',
        //     iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
        //     desc: '了解当前大模型可以帮你做的事',
        // },
        // {
        //     value: 'bindProjectSpace',
        //     label: '怎么绑定项目空间',
        //     iconConfig: { name: 'icon-priority', color: '#3ac295' },
        //     desc: '如何绑定云空间中的项目',
        // },
    ],
};
const simplePrompt = [
    {
        value: 'quickSort',
        iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
        label: '帮我写一个快速排序',
    },
    {
        value: 'helpMd',
        iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
        label: '你可以帮我做些什么？',
    },
];
const startPage = ref(true);
const inputValue = ref('');
const inputFootIcons = [
    { icon: 'icon-at', text: '智能体' },
    { icon: 'icon-standard', text: '词库' },
    { icon: 'icon-add', text: '附件' },
];

const messages = ref<any[]>([]);

const newConversation = () => {
    startPage.value = true;
    messages.value = [];
}

const onSubmit = async (evt) => {
    const userMessage = evt?.value?.trim() || inputValue.value.trim();
    if (!userMessage) {
        ElMessage.warning('请输入内容');
        return;
    }

    inputValue.value = '';
    startPage.value = false;

    messages.value.push({
        from: 'user',
        content: userMessage,
    });

    messages.value.push({
        from: 'model',
        content: '',
    });

    try {
        // 添加存在性判断
        if (!props.api.sendStreamMessage) {
            throw new Error('当前 API 不支持流式消息发送');
        }

        isLoading.value = true;
        var isThinking = false;

        const stream = await props.api.sendStreamMessage({
            id: props.id,
            message: userMessage,
        });

        const reader = stream.getReader();
        const decoder = new TextDecoder();
        var startTime = Date.now();
        let botReply = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value, { stream: true });
            // console.log('chunk', chunk);
            for (const data of parseSSE(chunk)) {
                botReply += data.message
            }

            messages.value[messages.value.length - 1].content = botReply;
            if (isThinking === false && messages.value[messages.value.length - 1].content.indexOf('<think>') > -1) {
                startTime = Date.now()
                isThinking = true
                thinkBtnText.value = '正在思考中...'
            }
            if (isThinking == true && messages.value[messages.value.length - 1].content.indexOf('</think>') > -1) {
                const endTime = Date.now();
                thinkBtnText.value = `已深度思考 (用时${(endTime - startTime) / 1000}秒)`;
                isThinking = false;
            }
            await nextTick();
        }

        isLoading.value = false;
        messages.value[messages.value.length - 1].loading = false;
    } catch (error) {
        console.error('流式请求失败:', error);
        ElMessage.error('流式请求失败，请稍后再试。');
    }
};
</script>

<style>
.rich-chat-dialog {
    --el-dialog-margin-top: 10vh;
    /* 设置为你想要的值，如 5vh、20px 等 */
}

.container {
    overflow: hidden;
    height: calc(80vh - 82px);
    margin: 0 auto;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    padding: 10px;
    background-color: #f9f9f9;
}

.content-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
    overflow: auto;
}

.input-foot-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100%;
    margin-right: 8px;

    .input-foot-left {
        display: flex;
        align-items: center;
        gap: 8px;

        span {
            font-size: 14px;
            line-height: 18px;
            color: #252b3a;
            cursor: pointer;
        }

        .input-foot-dividing-line {
            width: 1px;
            height: 14px;
            background-color: #d7d8da;
        }

        .input-foot-maxlength {
            font-size: 14px;
            color: #71757f;
        }
    }

    .input-foot-right {
        .demo-button-content {
            font-size: 14px;
        }

        &>*:not(:first-child) {
            margin-left: 8px;
        }
    }
}

.markdown-content {
    font-size: 15px;
    line-height: 1.7;
    color: #333;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3 {
    margin-top: 1.5em;
    margin-bottom: 0.5em;
    border-bottom: 1px solid #eee;
    padding-bottom: 4px;
}

.markdown-content p {
    margin-bottom: 1em;
}

.markdown-content a {
    color: #0366d6;
    text-decoration: underline;
}

.markdown-content ul,
.markdown-content ol {
    margin-left: 1.5em;
    margin-bottom: 1em;
}

.markdown-content code {
    background-color: #f0f0f0;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
}

.think-toggle-btn {
    display: flex;
    gap: 8px;
    align-items: center;
    border-radius: 10px;
    padding: 7px 10px;
    margin-bottom: 12px;
    width: fit-content;
    cursor: pointer;
    background-color: #f0f0f0;
    /* 替换 $devui-area 的值 */
}

.think-toggle-btn:hover {
    background-color: #e0e0e0;
    /* 替换 hover 效果 */
}

.shortcut {
    display: flex;
    align-items: center;
    gap: 8px;
    justify-content: space-between;
    width: 100%;
}

.botton {
    z-index: 150;
    width: 32px;
    height: 32px;
    background: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
    cursor: pointer;
    transition: all 0.3s ease;
    border: solid 1px rgba(0, 0, 0, 0.4);
}
</style>